package com.itheima.service.impl;

import com.itheima.Utils.MD5Utils;
import com.itheima.dao.MemberDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

@Service
public class MemberServiceImpl implements MemberService {
    @Autowired
    private MemberDao memberDao;
    @Override
    public Member findByTelePhone(String telephone) {
        return memberDao.findByTelephone(telephone);
    }

    @Override
    public void add(Member member) {
        String password = member.getPassword();
        if (password != null){
            String encrypt = MD5Utils.md5(password);
            member.setPassword(encrypt);
        }
        memberDao.add(member);
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        //基于mabatis的分页插件
        //通过startPage方法把数据绑定到线程
        //框架取出数据并拼接好sql select * from table limit 1,10
        PageHelper.startPage(currentPage,pageSize);
        Page<Member> page = memberDao.findByCondition(queryString);
        long total = page.getTotal();
        List<Member> rows = page.getResult();
        return new PageResult(total,rows);
    }

    @Override
    public Member findById(Integer id) throws Exception {
        return memberDao.findById(id);
    }

    @Override
    public void update(Member member) {
        memberDao.update(member);
    }

    @Override
    public void delete(Integer id) {
        memberDao.deleteById(id);
    }

    @Override
    public List<Integer> findMemberCountByMonths(List<String> months) {
        List<Integer> memberCount = new ArrayList<>();
        for (String month : months) {
            String date = month+".31";
            Integer count = memberDao.findMemberCountBeforDate(date);
            memberCount.add(count);
        }
        return memberCount;
    }
}
